package com.example.mediademo;

import static android.media.MediaCodecList.ALL_CODECS;

import static com.example.mediademo.muxer.MyMuxer.REPACK_FAILED;
import static com.example.mediademo.muxer.MyMuxer.REPACK_SUCCESS;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.media.MediaCodecInfo;
import android.media.MediaCodecList;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.mediademo.decode.AudioDecoder;
import com.example.mediademo.decode.BaseDecoder;
import com.example.mediademo.decode.Frame;
import com.example.mediademo.decode.VideoDecoder;
import com.example.mediademo.decode.interfaces.IDecodeStateListener;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class MainActivity extends AppCompatActivity {

    private SurfaceView surfaceView;
    private VideoDecoder videoDecoder;
    private AudioDecoder audioDecoder;
    private Button btnDecode;
    private Button btnEncode;
    private Button btnGetCodeList;
    private EditText etInput;
    private EditText etOutput;
    private TextView tvCodeList;
    private TextView tvMsg;


    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case REPACK_SUCCESS:
                    String fileName = (String) msg.obj;
                    tvMsg.setText("编码完成,文件路径:" + fileName);
                    break;
                case REPACK_FAILED:
                    String errorMsg = (String) msg.obj;
                    tvMsg.setText("编码失败:" + errorMsg);
                    break;
                case Mp4Repack.START_MUXER:
                    tvMsg.setText("开始生成MP4");
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        HandlerFactory.setMainHandler(mHandler);
        surfaceView = findViewById(R.id.sfv);
        initView();
        initData();
    }

    private void initData() {
        etInput.setText("/storage/emulated/0/h265_220419.mp4");
    }

    private void initView() {
        btnDecode = findViewById(R.id.btn_start_decode);
        btnEncode = findViewById(R.id.btn_start_encode);
        btnGetCodeList = findViewById(R.id.btn_getencode_list);
        etInput = findViewById(R.id.et_filepath);
        tvCodeList = findViewById(R.id.tv_codelist);
        tvMsg = findViewById(R.id.tv_msg);
        btnDecode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                initPlayer();
            }
        });
        btnEncode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                repack();
                tvMsg.setText("开始编码");
            }
        });
        btnGetCodeList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MediaCodecList mediaCodecList = new MediaCodecList(ALL_CODECS);
                MediaCodecInfo[] mediaCodecInfos = mediaCodecList.getCodecInfos();
                for (MediaCodecInfo info : mediaCodecInfos) {
                    String name = info.getName();
                    if (name.contains("avc") || name.contains("hevc")) {
                        tvCodeList.append(info.getName());
                        tvCodeList.append("  ");
                    }
                }
            }
        });
    }

    @Override
    protected void onPause() {
//        videoDecoder.pause();
//        audioDecoder.pause();
        super.onPause();
    }

    @Override
    protected void onResume() {
//        videoDecoder.resume();
//        audioDecoder.resume();
        super.onResume();
    }

    @Override
    protected void onDestroy() {
//        videoDecoder.stop();
//        audioDecoder.stop();
        super.onDestroy();
    }

    private void repack() {
        String filePath = etInput.getText().toString();
        if (filePath == null || filePath.equals("")) {
            Toast.makeText(this,"请输入正确路径",Toast.LENGTH_LONG).show();
            return;
        }
        Mp4Repack repack = new Mp4Repack(this,filePath);
        repack.start();
    }

    private void initPlayer() {
//        String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/mvtest.mp4";
        String filePath = etInput.getText().toString();
        if (filePath == null || filePath.equals("")) {
            Toast.makeText(this,"请输入正确路径",Toast.LENGTH_LONG).show();
            return;
        }
        Log.d(Configs.TAG,"path:" + filePath);
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2,20,60, TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>() );
        ExecutorService threadPool = threadPoolExecutor;
        // 视频解码
        videoDecoder = new VideoDecoder(filePath,surfaceView,null);
        threadPool.execute(videoDecoder);
        // 音频解码
//        audioDecoder = new AudioDecoder(filePath);
//        threadPool.execute(audioDecoder);

        videoDecoder.resume();
        Log.d(Configs.TAG,"BaseDecoder resume");
//        audioDecoder.resume();

        videoDecoder.setStateListener(new IDecodeStateListener() {
            @Override
            public void decodePrepare(BaseDecoder decodeJob) {

            }

            @Override
            public void decodeReady(BaseDecoder decodeJob) {

            }

            @Override
            public void decodeRunning(BaseDecoder decodeJob) {

            }

            @Override
            public void decodePause(BaseDecoder decodeJob) {

            }

            @Override
            public void decodeOneFrame(BaseDecoder decodeJob, Frame frame) {

            }

            @Override
            public void decodeFinish(BaseDecoder decodeJob) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this,"播放完毕",Toast.LENGTH_LONG).show();
                    }
                });
            }

            @Override
            public void decodeDestroy(BaseDecoder decodeJob) {

            }

            @Override
            public void decodeError(BaseDecoder decodeJob, String msg) {

            }
        });
    }

    /**
     *      MediaCodec分为两部分，input output，内部使用异步方式进行处理
     *      input:输入需要解码/编码的数据
     *      output:输出解码/编码后的数据
     *      处理结束后，需要手动清除output缓冲区，否则会导致codec缓冲区被占用，无法继续工作
     *      MediaCodec处理数据有三个状态 stopped executing released
     *      stoped: error uninitialized configured
     *      executing: flushed  running end of stream
     *      release
     *      新建MediaCodec： Uninitialized（调用configure）---> Configured(start)---> Flushed(dequeInputBuffer)
     *      --->Running(编/解码结束)--->EOS(end of stream)
     */

}